package com.itheima.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.exception.BusinessException;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class AdminManager {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    AdminService adminService;

    public LineCaptcha getVerification(String uuid) {
        //1.调用hutool中类生成带有干扰线的图片
        LineCaptcha lineCaptcha = new LineCaptcha(200,100);

        //2.将验证码存入redis中,时效5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE+uuid,lineCaptcha.getCode(), Duration.ofMinutes(5));

        //3.返回图片
        return lineCaptcha;
    }

    public ResponseEntity login(String username, String password, String requestCode, String uuid) {
        //1.判断验证码是否正确
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String redisCode = opsForValue.get(ConstantUtil.ADMIN_CODE + uuid);

        if (!StrUtil.equalsAnyIgnoreCase(redisCode,requestCode)) {
            //不一致,通知用户
            throw new BusinessException("请输入正确的验证码");
        }

        //2.远程调用service获取admin
        Admin admin = adminService.findByUsername(username);

        //3.判断admin是否为空
        if (admin == null) {
            throw new BusinessException("用户名输入错误");
        }

        //4.再次判断密码是否正确
        if (!StrUtil.equalsAnyIgnoreCase(admin.getPassword(), SecureUtil.md5(password))) {
            throw new BusinessException("请输入正确的密码");
        }

        //5.调用jwt生成token
        //建议将密码置空
        admin.setPassword(null);

        String token = JwtUtil.createToken(BeanUtil.beanToMap(admin));

        //6.将token做key,admin的json数据作为value存入redis中,时效1天
        opsForValue.set(ConstantUtil.ADMIN_TOKEN+token, JSON.toJSONString(admin),Duration.ofDays(1));

        //7.建议删除redis中验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE+uuid);

        //8.使用map封装token且返回
        Map<String,String> resultMap = new HashMap();
        resultMap.put("token",token);
        return ResponseEntity.ok(resultMap);
    }

    public void logout(String token) {
        token = token.replaceAll("Bearer ", "");
        //删除redis中该用户数据
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN+token);
    }
}
